<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/11/14
 * Time: 17:10
 * @link http://www.lmterp.cn
 */

namespace app\common\model;

class WarehouseLocation extends BaseModel
{
    protected $pk = 'location_id';

    protected $insert = ['create_by'];

    /**
     * 关联仓库
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/18
     * @author longli
     */
    public function warehouse()
    {
        return $this->belongsTo(Warehouse::class);
    }

    /**
     * 关联货架
     * @return \think\model\relation\BelongsTo
     * @date 2021/02/18
     * @author longli
     */
    public function shelf()
    {
        return $this->belongsTo(WarehouseShelf::class, 'shelf_id', 'shelf_id');
    }

    /**
     * 关联库存
     * @return \think\model\relation\HasOne
     * @date 2021/02/18
     * @author longli
     */
    public function stock()
    {
        return $this->hasOne(WarehouseStock::class, 'location_id', 'location_id');
    }

    /**
     * 库位编码是否存在
     * @param string $code 库位
     * @param int $warehouseId 仓库
     * @return bool
     * @date 2021/02/18
     * @author longli
     */
    public static function hasCode($code, $warehouseId = 0)
    {
        $location = static::where('code', trim($code));
        if(!empty($warehouseId)) $location->where('warehouse_id', intval($warehouseId));
        return !!$location->count();
    }

    /**
     * 释放库位
     * @param static|int $location 库位或者 id
     * @date 2021/02/21
     * @author longli
     */
    public static function releaseUsed($location)
    {
        if($location = static::getObj($location))
        {
            $location->is_used = static::IS_NO;
            $location->save();
        }
    }

    /**
     * 占用库位
     * @param static|int $location 库位或者 id
     * @date 2021/02/21
     * @author longli
     */
    public static function used($location)
    {
        if($location = static::getObj($location))
        {
            $location->is_used = static::IS_YES;
            $location->save();
        }
    }

    /**
     * 生成库位
     * @param string $prefix 前缀
     * @return string
     * @date 2021/02/18
     * @author longli
     */
    public static function generateCode($prefix = '', $len = 8)
    {
        do
        {
            $rand = \app\common\library\Tools::getRandStr($len, 2);
            $code = $prefix . strtoupper($rand);
        }while(static::hasCode($code));
        return $code;
    }
}
